package com.upload;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by ${oushuhua} on 2017/5/10.
 */

public class ImageUtil {
    private LruCache<String, Bitmap> mCache = null;
    private static ImageUtil imgUtil = null;

    private ImageUtil() {
        mCache = new LruCache<String, Bitmap>((int) (Runtime.getRuntime().maxMemory() / 8)) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getRowBytes() * value.getHeight();
            }
        };
    }

    public static ImageUtil getInstance() {
        if (imgUtil == null) {
            synchronized (ImageUtil.class) {
                if (null == imgUtil) {
                    imgUtil = new ImageUtil();
                }
            }
        }
        return imgUtil;
    }

    public Bitmap put(String key, Bitmap value) {
        return mCache.put(key, value);
    }

    public Bitmap get(String key) {
        return mCache.get(key);
    }

    /**
     * 将图片压缩至指定容量以下
     *
     * @param maxSize 单位kb
     */
    public static byte[] compressImage(Bitmap imgBm, int maxSize) {
        if (null == imgBm) {
            return null;
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        imgBm.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > maxSize && options > 10) { // 循环判断如果压缩后图片是否大于指定值,大于继续压缩并且保证optuins大于10
            baos.reset();// 重置baos即清空baos
            options -= 10;// 每次都减少10
            imgBm.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
        }
        return baos.toByteArray();
    }


    /**
     * 获取本地图片并压缩至指定宽高
     *
     * @param tarWid 最终图片的wid
     * @param tarHei 最终图片的hei
     */
    public static Bitmap decodeScaleImage(String path, int tarWid, int tarHei) {
        BitmapFactory.Options options = getBitmapOptions(path);
        int calculateSize = calculateInSampleSize(options, tarWid, tarHei);
        Log.i("img", "original wid" + options.outWidth + " original height:" + options.outHeight + " sample:" + calculateSize);
        options.inSampleSize = calculateSize;
        options.inJustDecodeBounds = false;
        Bitmap bm = BitmapFactory.decodeFile(path, options);
        int rota = readPictureDegree(path);
        Bitmap rotaBm;
        if (bm != null && rota != 0) {
            rotaBm = rotaingImageView(rota, bm);
            bm.recycle();
            return rotaBm;
        } else {
            return bm;
        }
    }

    public static BitmapFactory.Options getBitmapOptions(String var0) {
        BitmapFactory.Options var1 = new BitmapFactory.Options();
        var1.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(var0, var1);
        return var1;
    }

    /**
     * 根据最终图片尺寸，计算压缩比例
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int tarWid, int tarHei) {
        int height = options.outHeight;
        int width = options.outWidth;
        int inSampleSize = 1;

        if (height > tarHei || width > tarWid) {

            int halfHeight = height / 2;
            int halfWidth = width / 2;

            // 在保证解析出的bitmap宽高分别大于目标尺寸宽高的前提下，取可能的inSampleSize的最大值
            while ((halfHeight / inSampleSize) > tarHei
                    && (halfWidth / inSampleSize) > tarWid) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    /**
     * 计算图片旋转方向
     */
    public static int readPictureDegree(String imgPath) {
        short var1 = 0;

        try {
            ExifInterface exifInterface = new ExifInterface(imgPath);
            int result = exifInterface.getAttributeInt("Orientation", 1);
            switch (result) {
                case 3:
                    var1 = 180;
                    break;
                case 6:
                    var1 = 90;
                    break;
                case 8:
                    var1 = 270;
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return var1;
    }

    /**
     * 返回正确方向的图片
     */
    public static Bitmap rotaingImageView(int var0, Bitmap var1) {
        Matrix var2 = new Matrix();
        var2.postRotate((float) var0);
        Bitmap var3 = Bitmap.createBitmap(var1, 0, 0, var1.getWidth(), var1.getHeight(), var2, true);
        return var3;
    }
}
